#include "homepage.h"
#include "ui_homepage.h"
#include "globalval.h"
#include <QFile>
HomePage::HomePage(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::HomePage)
{
    ui->setupUi(this);

    QFile qss_file(":/qss/style/homepage.qss");
    if (qss_file.open(QFile::ReadOnly)) {
        QString qss_text = QLatin1String(qss_file.readAll());
        ui->listWidget->setStyleSheet(qss_text);
        qss_file.close();
    }

    //实例化四个界面
    home = new Home;
    stm32Wig = new Stm32Wig;
    modbusWig = new ModbusWig;
    mbappWig = new MbappWig;
    setWig = new SetWig;
    history = new History;
    opencv = new Opencv;

    //将四个界面依次添加到堆栈窗体
    ui->stackedWidget->addWidget(home);
    ui->stackedWidget->addWidget(stm32Wig);
    ui->stackedWidget->addWidget(modbusWig);
    ui->stackedWidget->addWidget(history);
    ui->stackedWidget->addWidget(opencv);
    ui->stackedWidget->addWidget(mbappWig);
    //ui->stackedWidget->addWidget(setWig);



    //连接列表界面和堆栈窗体的信号
    QObject::connect(ui->listWidget, SIGNAL(currentRowChanged(int)),
                     ui->stackedWidget, SLOT(setCurrentIndex(int)));

    //mqtt相关
    MqttHandler *mqtt = new MqttHandler;
    GlobalVal::mqtt = mqtt;
    mqtt->setHost(QHostAddress("192.168.43.125"));
    mqtt->setPort(1883);
    mqtt->connectToHost();

    //哪个界面需要接收Mqtt的消息，就订阅这个信号，然后在自己的界面文件中处理消息
    QObject::connect(mqtt, SIGNAL(dataUpSignal(QByteArray)),
                     stm32Wig, SLOT(dataUpSlot(QByteArray)));
    QObject::connect(mqtt, SIGNAL(dataUpSignal(QByteArray)),
                     modbusWig, SLOT(dataUpSlot(QByteArray)));
    QObject::connect(mqtt, SIGNAL(dataUpSignal(QByteArray)),
                     history, SLOT(dataUpSlot(QByteArray)));



    connect(stm32Wig, SIGNAL(sendmessage(QByteArray)),
                         this, SLOT(dataSendSlot(QByteArray)));
    connect(home, SIGNAL(sendmessage(QByteArray)),
                         this, SLOT(dataSendSlot(QByteArray)));
    connect(history, SIGNAL(sendmessage(QByteArray)),
                         this, SLOT(dataSendSlot(QByteArray)));


}

HomePage::~HomePage()
{
    delete ui;
}



void HomePage::dataSendSlot(QByteArray str)
{
    QString jsonStr(str);
    qDebug()<<jsonStr;
    QString mqttser="192.168.43.125";
    quint16 serid = mqttser.toUInt();
    QMQTT::Message message(serid,"/app/control/down",str);
    GlobalVal::mqtt->publish(message);
}
